package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private RoomInfoMapper roomInfoMapper;

    @Override
    public IPage<ApartmentItemVo> getPageList(Page<ApartmentItemVo> apartmentItemVoPage, ApartmentQueryVo queryVo) {
        return baseMapper.getPageList(apartmentItemVoPage,queryVo);
    }

    @Override
    public void saveOrUpdateApartmentInfo(ApartmentSubmitVo apartmentSubmitVo) {
        // 获取公寓id（把获取id放在最前面，如果没有id 保存，有id 更新。）
        Long apartmentId = apartmentSubmitVo.getId();

        // 调用 mybatis-plus 自带的方法，保存或更新公寓信息
        saveOrUpdate(apartmentSubmitVo);

        // 下面代码是更新的逻辑（一个比较简单的实现方式，先删除原来的数据，再插入新的数据，实现更新。）
        // apartmentId 是否为null
        if (apartmentId != null) {
            // 不为null，更新，删除中间表的数据
            // 1. 根据公寓id删除，公寓配套
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            // 封装查询条件
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentId);
            // 调用带条件的删除
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
            // 2. 根据公寓id删除，公寓标签
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,apartmentId));
            // 3. 根据公寓id删除，公寓杂费值
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,apartmentId));
            // 4. 根据公寓id 和图片类型 删除，公寓图片
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,apartmentId).eq(GraphInfo::getItemType,ItemType.APARTMENT));
        }

        // 1. 保存公寓配套
        // 获取公寓的配套id
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        // 验空[ 如果 facilityInfoIds 集合不为空]
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            // 创建一个集合
            List<ApartmentFacility> apartmentFacilityList = new ArrayList<>();
            // 遍历所有的配套id
            for (Long facilityInfoId : facilityInfoIds) {
                // 创建 ApartmentFacility 对象
                ApartmentFacility apartmentFacility = ApartmentFacility.builder().facilityId(facilityInfoId).apartmentId(apartmentSubmitVo.getId()).build();
                // 添加到集合中
                apartmentFacilityList.add(apartmentFacility);
            }
            // 批量保存
            apartmentFacilityService.saveBatch(apartmentFacilityList);
        }

        // 2. 保存公寓标签
        // 获取公寓的标签id
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        //  验空
        if (!CollectionUtils.isEmpty(labelIds)) {
            // 创建一个集合
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>();
            // 遍历所有的标签id
            for (Long labelId : labelIds) {
                // 创建 ApartmentLabel 对象
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().labelId(labelId).apartmentId(apartmentSubmitVo.getId()).build();
                // 添加到集合中
                apartmentLabelList.add(apartmentLabel);
            }
            // 批量保存
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        // 3. 保存公寓杂费值
        // 获取公寓的杂费值id
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        // 验空
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            // 创建一个集合
          List<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>();
            // 遍历所有的杂费值id
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().feeValueId(feeValueId).apartmentId(apartmentSubmitVo.getId()).build();
                // 添加到集合中
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            // 批量保存
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }

        // 4. 保存公寓图片
        // 获取公寓图片信息(GraphVo)
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        // 验空
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo>  graphInfoList = new ArrayList<>();
            for (GraphVo graphVo : graphVoList) {
                // 创建 GraphInfo对象
                GraphInfo graphInfo = new GraphInfo();
                // 设置图片的名字
                graphInfo.setName(graphVo.getName());
                // 设置图片的url
                graphInfo.setUrl(graphVo.getUrl());
                // 设置公寓的id
                graphInfo.setItemId(apartmentSubmitVo.getId());
                // 设置图片的类型
                graphInfo.setItemType(ItemType.APARTMENT);
                // 添加到集合中
                graphInfoList.add(graphInfo);
            }
            // 批量保存
            graphInfoService.saveBatch(graphInfoList);
        }
    }

    @Override
    public ApartmentDetailVo getApartmentDetailVoById(Long id) {
        // 调用 mybatis-plus 自带的方法查询公寓
        ApartmentInfo apartmentInfo = getById(id);

        // 1. 根据公寓id和图片类型，查询公寓的图片（图片列表）
        List<GraphVo> graphVoList = graphInfoMapper.getGraphVoApartmentIdAndItemType(id,ItemType.APARTMENT);
        // 2. 根据公寓id，查询公寓的标签
        List<LabelInfo> labelInfoList = labelInfoMapper.getLabelInfoListByApartmengtId(id);
        // 3. 根据公寓id，查询公寓配套列表
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.getFacilityInfoListByApartmengtId(id);
        // 4.  根据公寓id，查询杂费列表
        List<FeeValueVo> feeValueVoList = feeValueMapper.getFeevalueVoListByApartmengtId(id);

        // 创建 返回的对象
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        // 设置公寓信息
        // 下面这行代码，可以单一属性值赋值；但是属性值有多个，麻烦，可以使用 BeanUtils 工具类
//        apartmentDetailVo.setName(apartmentInfo.getName());
        // 使用 BeanUtils 工具类赋值（将两个对象的，同名属性值，赋值）
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);

        // 设置图片
        apartmentDetailVo.setGraphVoList(graphVoList);
        // 设置标签
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        // 设置配套
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        // 设置杂费
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        return apartmentDetailVo;
    }

    @Override
    public void deleteApartmentInfoById(Long apartmentId) {
        // 判断该公寓下是否有房间
        Long count = roomInfoMapper.selectCount(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, apartmentId));
        if (count > 0) {
            // 该公寓下有房间，不能删除
//            throw new RuntimeException("该公寓下有房间，不能删除");
            throw new LeaseException(ResultCodeEnum.HAS_ROOM);
        }

        // 调用 Mybatis-plus 自带的方法删除公寓信息
        removeById(apartmentId);

        // 删除中间表的数据
        // 1. 根据公寓id删除，公寓配套
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 封装查询条件
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentId);
        // 调用带条件的删除
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
        // 2. 根据公寓id删除，公寓标签
        apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,apartmentId));
        // 3. 根据公寓id删除，公寓杂费值
        apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,apartmentId));
        // 4. 根据公寓id 和图片类型 删除，公寓图片
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,apartmentId).eq(GraphInfo::getItemType,ItemType.APARTMENT));

    }
}
